import Toast from '@vant/weapp/toast/toast'
import api from '../../api/api'
import Notify from '@vant/weapp/notify/notify'
Page({
  data: {
    codeShow: true,
    email: '',
    checkCode: '',
    count: ''
  },
  toHome() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  async getCode() {
    const all = 60
    let timer = null
    if (timer == null) {
      const res = await api.emailValidCode({ email: this.data.email })
      console.log('获取验证码', res)
      if (res.data.code == "J001") {
        Notify({ type: 'success', message: res.data.msg })
        this.setData({
          count: all,
          codeShow: false
        })
        timer = setInterval(() => {
          if (this.data.count > 0 && this.data.count <= all) {
            this.setData({
              count: this.data.count - 1
            })
          } else {
            this.setData({
              codeShow: true
            })
            clearInterval(timer);
            timer = null
          }
        }, 1000)
      } else {
        Toast.fail(res.data.msg)
      }
    }
  },
  async next(e) {
    let email = e.detail.value.email
    const emailReg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
    let checkCode = e.detail.value.checkCode
    if (email == '') {
      Toast.fail('邮箱不能为空')
      return
    }
    if (checkCode == '') {
      Toast.fail('验证码不能为空')
      return
    }
    if (!emailReg.test(email)) {
      Toast.fail('这是一个错误的邮箱')
      return
    }
    const res = await api.checkValidCode({ validCode: this.data.checkCode })
    console.log('验证码验证', res)
    if (res.data.code == 'K001') {
      Toast.success(res.data.msg)
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/find-password-second/find-password-second',
        })
      }, 1500)
    } else {
      Toast.fail(res.data.msg)
    }
  },
  onLoad(options) {
  },
  onShow() {
  },
})